package CreationalPatterns;

/**
 * 所谓单例模式就是,保障对象是唯一实例
 */

/**
 * 饿汉模式,线程是安全的
 */
class Singleton1{
    private static Singleton1 instance=new Singleton1();
    public static Singleton1 getInstance(){
        return instance;
    }
    private Singleton1(){

    }
}

/**
 * 懒汉模式,线程是不安全的
 */
class Singleton2{
    private static volatile Singleton2 instance=null;
    private static Object locker=new Object();
    public static Singleton2 getInstance(){
       if(instance==null){
           synchronized (locker){
               if(instance==null) {
                   instance = new Singleton2();
               }
           }
       }
        return instance;
    }
}

public class Singleton {
    public static void main(String[] args) {
        Singleton1 instance = Singleton1.getInstance();
        Singleton1 instance1 = Singleton1.getInstance();
        System.out.println(instance==instance1);
    }


}
